<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="mx-auto px-4">
      <!-- 搜索区域 -->
      <div class="search-bar">
        <el-form :inline="true" :rule="formRules">
          <el-form-item label="产品名称" prop="productName">
            <el-select
              v-model="productName"
              clearable
              class="!w-[192px]"
              placeholder="请选择产品名称"
              filterable
            >
              <el-option
                v-for="item in productList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="生产批次号" prop="batchCode">
            <el-select
              v-model="batchCode"
              class="!w-[192px]"
              filterable
              clearable
              remote
              :remote-method="getTProdHeadList"
              placeholder="请选择生产批次号"
              @change="batchCodeChange"
            >
              <el-option
                v-for="(item, index) in sourceCodeList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
              <!-- <el-option label="G21221400" value="G21221400" /> -->
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="!rounded-button whitespace-nowrap"
              @click="handleSearch"
            >
              查询
            </el-button>
            <el-button class="!rounded-button whitespace-nowrap" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 主要内容区域 -->
      <div class="relative flex">
        <div class="flex-1 bg-white rounded-lg shadow-sm p-6">
          <div v-if="isFormComplete" class="timeline relative">
            <!-- 原材料入库 -->
            <div class="timeline-item pb-12">
              <div class="flex items-start">
                <div class="timeline-icon bg-green-100 rounded-lg p-2">
                  <el-icon class="text-green-600 text-xl"><Box /></el-icon>
                </div>
                <div class="ml-4 flex-1">
                  <el-card>
                    <h3 class="text-lg font-medium mb-4">原材料入库</h3>
                    <div class="grid grid-cols-3 gap-8">
                      <div class="space-y-2">
                        <div class="text-gray-500">入库时间</div>
                        <div>{{ tableData.inboundTime }}</div>
                      </div>
                      <div class="space-y-2">
                        <div class="text-gray-500">供应商名称</div>
                        <div>{{ tableData.supplierName }}</div>
                      </div>
                      <div class="space-y-2">
                        <div class="text-gray-500">供应商编号</div>
                        <div>{{ tableData.supplierCode }}</div>
                      </div>
                    </div>
                    <div class="mt-4">
                      <div class="text-gray-500">原材料名称</div>
                      <div class="mt-1">{{ tableData.materialName }}</div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>

            <!-- 生产环境 -->
            <div class="timeline-item pb-12">
              <div class="flex items-start">
                <div class="timeline-icon bg-blue-100 rounded-lg p-2">
                  <el-icon class="text-blue-600 text-xl"><Setting /></el-icon>
                </div>
                <el-card class="ml-4 flex-1">
                  <h3 class="text-lg font-medium mb-4">生产环境</h3>
                  <div class="grid grid-cols-3 gap-8">
                    <div class="space-y-2">
                      <div class="text-gray-500">质检报告</div>
                      <!-- <el-button type="primary" link class="!rounded-button whitespace-nowrap">
                        查看
                      </el-button> -->
                      <FileUpload
                        v-model="tableData.reportImage"
                        :showUploadBtn="false"
                        :showDelBtn="false"
                        :data="{ bizType: 'contract' }"
                        style="width: 100%"
                      />
                    </div>
                    <div class="space-y-2">
                      <div class="text-gray-500">生产批次号</div>
                      <div>{{ tableData.productionCode }}</div>
                    </div>
                    <div class="space-y-2">
                      <div class="text-gray-500">生产日期</div>
                      <div>{{ planDate }}</div>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>

            <!-- 产品入库 -->
            <div class="timeline-item">
              <div class="flex items-start">
                <div class="timeline-icon bg-gray-100 rounded-lg p-2">
                  <el-icon class="text-gray-600 text-xl"><Goods /></el-icon>
                </div>
                <el-card class="ml-4 flex-1">
                  <h3 class="text-lg font-medium mb-4">产品入库</h3>
                  <div class="grid grid-cols-3 gap-8">
                    <div class="space-y-2">
                      <div class="text-gray-500">入库时间</div>
                      <div>{{ tableData.inboundTime }}</div>
                    </div>
                    <div class="space-y-2">
                      <div class="text-gray-500">产品名称</div>
                      <div>{{ tableData.productName }}</div>
                    </div>
                    <div class="space-y-2">
                      <div class="text-gray-500">生产批次号</div>
                      <div>{{ tableData.productionCode }}</div>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </div>
          <div v-else style="text-align: center">暂无数据</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { Box, Setting, Goods } from "@element-plus/icons-vue";
import productTraceabilityAPI, { traceInfo } from "@/api/productTraceability/productTraceability";
import planOrderApi from "@/api/planManage/planOrderManage";
import productBomAPI from "@/api/productBom/productBom";

import qualityAPI, {
  QualityControlInquire,
  QualityControlInfo,
  QualityControlTab,
} from "@/api/quality/quality";
import { ElMessage } from "element-plus";

// const traceInfo =
const productName = ref("");
const batchCode = ref("");
const isShow = ref(false);
const planDate = ref("");
interface tableData {
  inboundTime?: string;
  materialName?: string;
  productCode?: string;
  productName?: string;
  productionCode?: string;
  supplierCode?: string;
  supplierName?: string;
  reportImage?: [];
}

const tableData = reactive<tableData>({
  inboundTime: "",
  materialName: "",
  productCode: "",
  productName: "",
  productionCode: "",
  supplierCode: "",
  supplierName: "",
  reportImage: [],
});

const isFormComplete = computed(() => {
  let a = Object.values(tableData).find(
    (value) => value != "" || (Array.isArray(value) && value.length !== 0)
  );
  // console.log(a == "");
  if (a) {
    return true;
  } else {
    return false;
  }

  // for (let item in tableData) {
  //   console.log(tableData[item]);
  // }
});
const sourceCodeList = ref<
  {
    label: string;
    value: string;
    planDate: string;
  }[]
>([]);
const productList = ref<
  {
    label: string;
    value: string;
  }[]
>([]);
const queryParams = reactive<QualityControlInquire>({
  pageNum: 1,
  pageSize: 10,
});

const handleSearch = () => {
  if (!productName.value || !batchCode.value) {
    return ElMessage.warning("请选择产品名称或产品批次号");
  }
  clearForm();
  getInfo();
};
const clearForm = () => {
  let tab = {
    inboundTime: "",
    materialName: "",
    productCode: "",
    productName: "",
    productionCode: "",
    supplierCode: "",
    supplierName: "",
    reportImage: [],
  };
  Object.assign(tableData, tab);
};
const handleReset = () => {
  productName.value = "";
  batchCode.value = "";
  clearForm();
};
const getProductName = async () => {
  try {
    const response = await productBomAPI.getTypePage({
      pageNum: 1,
      pageSize: 20,
      productType: "1",
    });
    const dataList = response?.list || [];

    productList.value = dataList.map((item: any) => ({
      value: item.code,
      label: item.productName,
    }));
  } catch (error) {
    console.error("Error fetching product types:", error);
  }
};
const batchCodeChange = (val: string) => {
  let data = sourceCodeList.value.find((item) => item.value == val);
  planDate.value = data?.planDate as string;
};
const qualityImg = () => {
  queryParams.parentCode = batchCode.value;
  // queryParams.parentCode = "PROD2025021700000368";
  queryParams.productName = productName.value;
  qualityAPI
    .getPage(queryParams)
    .then((data) => {
      if (data?.list[0]?.reportImage) {
        let img = data?.list[0]?.reportImage.map((item: any) => {
          return {
            name: item.split("/").pop(),
            url: item,
          };
        });

        tableData.reportImage = img as any;
      }

      console.log(tableData);
    })
    .finally(() => {
      // loading.value = false;
    });
};
// 获取生产批次号
const getTProdHeadList = (query: string) => {
  let data = {
    pageNum: 1,
    pageSize: 999,
    statusList: [5, 6],
  };
  console.log(data);
  planOrderApi
    .getPage(data)
    .then((data: any) => {
      console.log(data);
      let list = data?.list.map((item: any) => {
        return {
          label: item.code,
          value: item.code,
          planDate: item.planDate,
        };
      });
      sourceCodeList.value = [...(list as any)];
    })
    .catch((err) => {
      console.log(err);
      // ElMessage.error(`${err}`);
      // handleCloseDialog();
      // handleResetQuery();
    })
    .finally(() => {
      // loading.value = false;
    });
};
const getInfo = () => {
  let data = {
    // productionCode: "PROD2025021700000368",
    productionCode: batchCode.value,
    productName: productName.value,
  };
  console.log(data);
  productTraceabilityAPI
    .getTrace(data)
    .then((data) => {
      console.log(data);
      if (data.length != 0) {
        tableData.inboundTime = data[0].inboundTime;
        tableData.materialName = data[0].materialName;
        tableData.productCode = data[0].productCode;
        tableData.productName = data[0].productName;
        tableData.productionCode = data[0].productionCode;
        tableData.supplierCode = data[0].supplierCode;
        tableData.supplierName = data[0].supplierName;
      }
      qualityImg();
      // isFormComplete();
    })
    .finally(() => {
      // loading.value = false;
    });
};

const formRules = reactive({
  productName: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
  batchCode: [{ required: true, message: "请选择生产批次号", trigger: "change" }],
});
onMounted(() => {
  // getInfo();
  getProductName();
});
</script>

<style scoped>
.timeline {
  position: relative;
}

.timeline::before {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 16px;
  width: 2px;
  content: "";
  background-color: #e5e7eb;
}

.timeline-item {
  position: relative;
}

.timeline-icon {
  position: relative;
  z-index: 1;
}

.timeline-item:last-child {
  padding-bottom: 0;
}
</style>
